<script setup>
import { ref, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import { deleteHandler, restartHandler, updateHandler } from '../../api/Generic.js'
import { getReplicaSetListHandler } from '../../api/deployment.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue';
import MatchPod from './MatchPod.vue';
import { object2String, obj2Yaml } from '../../utils/utils.js'
import CodeMirror from './CodeMirror.vue'

const router = useRouter()
const props = defineProps({
  resourceType: {
    type: String,
    default: 'Deployment'
  },
  clusterId: {
    type: String,
    required: true
  },
  namespace: {
    type: String,
    default: ''
  },
  name: {
    type: String,
    required: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  showScheduleOptions: {
    type: Boolean,
    default: false
  },
  item: {
    type: Object,
    default: {}
  }
})

const emits = defineEmits(['deleteRollback'])
// 删除的方法
const deleteItem = () => {
  let message = ''
  if(props.namespace == '') {
    message = `确定删除${props.resourceType}: ${props.name}吗？`
  }else{
    message = `确定删除名称空间:${props.namespace} ${props.resourceType}: ${props.name}吗？`
  }
  ElMessageBox.confirm(
        message,
        'Warning',
        {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        }
    ).then(() => {
      deleteHandler(props.clusterId, props.namespace, props.name, props.resourceType).then(
        (res) => {
          ElMessage({
              message: res.data.message,
              type: 'success',
          })
        //   getList()
        emits('deleteRollback')
        }
      )
    }).catch(() => {
        return
    })
}
const editItem = (arg) => {
  console.log("编辑或复制资源", props.clusterId, props.namespace, props.name)
  const resourceType = props.resourceType.toLowerCase()
  router.push({
    path: `/${resourceType}/edit`,
    query: {
      clusterId: props.clusterId,
      namespace: props.namespace,
      name: props.name,
      method: arg
    }
  })
}
const restart = () => {
  console.log("重启的资源", props.clusterId, props.namespace, props.resourceType, props.name)
  ElMessageBox.confirm(
    `确定重启${props.namespace} ${props.resourceType.toLocaleLowerCase()}/${props.name}吗？`,
    'warning',
    {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    }
  ).then(() => {
    restartHandler(props.clusterId, props.namespace, props.resourceType, props.name).then((res) => {
      ElMessage({
        message: res.data.message,
        type: 'success'
      })
    })
  }).catch(() => {
    return
  })
}
const updateImages = ref(false)
const rollback = ref(false)
const rollbackSelected = ref()
const updateImagesFormRef = ref(false)
const activeName = ref(0)
let disabledUpdateImageButton = ref(true)
const handleCommand = (command) => {
  console.log("你点击了：", command)
  switch (command) {
    case 'updateImages':
      updateImages.value = true
      break;
    case 'rollback':
      rollback.value = true
      break;
    default:
      break;
  }
}
const updateContainerImage = () => {
  updateImagesFormRef.value.validate((valid) => {
    if(valid) {
      console.log("修改后的值:",props.item)
      ElMessageBox.confirm(
        `确定更新${props.clusterId}集群:${props.namespace} ${props.resourceType.toLocaleLowerCase()}/${props.name}镜像吗？`,
        'warning',
        {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        }
      ).then(() => {
        updateHandler(props.clusterId, props.namespace, props.name, props.resourceType, props.item).then((res) => {
          updateImages.value = false
          ElMessage({
            message: res.data.message,
            type: 'success'
          })
          emits('deleteRollback')
        })
      }).catch(() => {
        return
      })
    }else{
      ElMessage.warning("请输入镜像地址")
      disabledUpdateImageButton.value = true
    }
  })
}
const rollbackDeploymentHandler = (item, rsTemplate) => {
  ElMessageBox.confirm(
    `确定回滚${props.clusterId}集群:${props.namespace} ${props.resourceType.toLocaleLowerCase()}/${props.name}镜像吗？`,
    'warning',
    {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    }
  ).then(() => {
    item.spec.template = rsTemplate
    delete item.spec.template.metadata.labels['pod-template-hash']
    updateHandler(props.clusterId, props.namespace, props.name, props.resourceType, item).then((res) => {
      rollback.value = false
      ElMessage({
        message: res.data.message,
        type: 'success'
      })
      emits('deleteRollback') //重新获取列表
    })
  }).catch(() => {
    return
  })
}
let containers = ref([])
let rsList = ref([])
let yamlData = ref('')
const visibleChanged = (visible) => {
  if(visible){
    const labelSelector = object2String(props.item.spec.selector.matchLabels,",")
    const getData = {
      clusterId: props.clusterId,
      namespace: props.namespace,
      fieldSelector: '',
      labelSelector: labelSelector
    }
    getReplicaSetListHandler(getData).then((res) => {
      let items = res.data.data.items
      items.sort(
        (a, b) => 
        b.metadata.annotations['deployment.kubernetes.io/revision'] -
        a.metadata.annotations['deployment.kubernetes.io/revision']
        )
      // 排序
      rsList.value = items
      console.log(rsList.value)
    })
  }
}
const rollbackChanged = () => {
  console.log("选择回滚的版本是:", rollbackSelected.value)
  const item = JSON.parse(JSON.stringify(rollbackSelected.value))
  delete item.metadata.managedFields
  const itemtemp = {
    "apiVersion": "apps/v1",
    "kind": "ReplicaSet",
    "metadata": item.metadata,
    "spec": item.spec
  }
  yamlData.value = obj2Yaml(itemtemp)
}
const rollbackDeployment = () => {
  console.log("回滚的RS:", rollbackSelected.value.spec.template)
  console.log("当前deployment配置:", props.item)
  rollbackDeploymentHandler(JSON.parse(JSON.stringify(props.item)), rollbackSelected.value.spec.template)
}
onBeforeMount(() => {
  // if (props.item =! null) {
  //   if (['Deployment','StatefulSet','DaemonSet'].includes(props.resourceType)) {
  //     containers.value = props.item.spec.template.spec.containers
  //   } else if (props.resourceType == 'CronJob') {
  //     containers.value = props.item.spec.jobTemplate.spec.template.spec.containers
  //   }
  // }
  if (['Deployment','StatefulSet','DaemonSet'].includes(props.resourceType)) {
      containers.value = props.item.spec.template.spec.containers
    } else if (props.resourceType == 'CronJob') {
      containers.value = props.item.spec.jobTemplate.spec.template.spec.containers
    }
})
</script>
<template>
  <el-button :disabled="props.disabled" link type="warning" @click="deleteItem()">删除</el-button>
  <el-button :disabled="props.disabled" link type="success" @click="restart()" v-if="['Deployment','StatefulSet','DaemonSet'].includes(props.resourceType)">重启</el-button>
  <el-button :disabled="props.disabled" link type="primary" @click="editItem('Update')">编辑</el-button>
  <el-button :disabled="props.disabled" link type="primary" @click="editItem('Copy')">复制</el-button>
  <el-dropdown v-if="props.showScheduleOptions" @command="handleCommand">
    <span>
        <el-button link type="primary" style="height: 25px; margin-left: 10px;">更多
          <el-icon>
            <ArrowDown/>
          </el-icon>
        </el-button>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="rollback" v-if="props.resourceType == 'Deployment'">回滚</el-dropdown-item>
        <el-dropdown-item command="updateImages">镜像更新</el-dropdown-item>
        <el-dropdown-item v-if="props.resourceType != 'CronJob'">
          <MatchPod
          :cluster-id="props.clusterId"
          button-name="关联pod"
          :resource-type="props.resourceType"
          :resource-name="props.name"
          :label-selector-obj="props.item.spec.selector.matchLabels"
          field-selector=""
          button-type="primary"
          ></MatchPod>
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>

  <!-- 更新镜像 -->
  <el-dialog append-to-body width="70%" center draggable v-model="updateImages">
      <template #header="{ titleId, titleClass }">
          <div :id="titleId" :class="titleClass" style="margin: 10px auto 0 auto;">
              <el-tag class="el-tag" size="large" title="集群">{{ props.clusterId }}</el-tag>>
              <el-tag class="el-tag" size="large" title="命名空间">{{ props.namespace }}</el-tag>>
              <el-tag class="el-tag" size="large" title="类型">{{ props.resourceType }}</el-tag>>
              <el-tag class="el-tag" size="large" title="资源名称">{{ props.name }}</el-tag>
          </div>
      </template>
      <el-form :model="containers" ref="updateImagesFormRef" >
        <el-tabs v-model="activeName">
          <el-tab-pane v-for="(c, index) in containers" :label="c.name" :name="index" :key="c.name">
              <el-form-item label="镜像"
              :rules="[{required: true, message: '请输入镜像地址', trigger: 'blur'}]"
              :prop="index + '.image'">
                <el-input v-model.trim="c.image" style="width: 320px;" @change="() => {disabledUpdateImageButton=false}"/>
              </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <el-button @click="updateImages=false">取消</el-button>
        <el-button :disabled="disabledUpdateImageButton" @click="updateContainerImage()" type="primary">确认</el-button>
      </template>
  </el-dialog>
  <!-- 回滚 -->
  <el-dialog append-to-body width="70%" center draggable v-model="rollback">
      <template #header="{ titleId, titleClass }">
          <div :id="titleId" :class="titleClass" style="margin: 10px auto 0 auto;">
              <el-tag class="el-tag" size="large" title="集群">{{ props.clusterId }}</el-tag>>
              <el-tag class="el-tag" size="large" title="命名空间">{{ props.namespace }}</el-tag>>
              <el-tag class="el-tag" size="large" title="类型">{{ props.resourceType }}</el-tag>>
              <el-tag class="el-tag" size="large" title="资源名称">{{ props.name }}</el-tag>
          </div>
      </template>
      <div>
        <el-form-item label="当前版本:">
          <span>{{ props.item.metadata.annotations["deployment.kubernetes.io/revision"] }}</span>
        </el-form-item>
        <el-form-item label="选择回滚版本:">
          <el-select value-key="metadata.name" v-model="rollbackSelected" placeholder="请选择回滚的版本" @visible-change="visibleChanged" @change="rollbackChanged">
            <el-option v-for="item in rsList"
            :key="item.metadata.name"
            :label="'版本:' + item.metadata.annotations['deployment.kubernetes.io/revision'] + 
            '  ' + item.metadata.annotations['kubernetes.io/change-cause']"
            :value="item"/>
          </el-select>
        </el-form-item>
      </div>
      <!-- 展示yaml -->
      <div>
        <CodeMirror v-model="yamlData" height="200px"
        ></CodeMirror>
      </div>
      <template #footer>
        <el-button @click="rollback=false">取消</el-button>
        <el-button @click="rollbackDeployment()" type="primary">确认</el-button>
      </template>
  </el-dialog>
</template>
<style lang="less" scoped>
.el-tag {
    margin-left: 20px;
    margin-right: 20px;
    font-size: 20px;
}

</style>